package book;

import com.bit.utils.FileUtils;

import java.time.LocalDate;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 32309
 * Date: 2025-07-17
 * Time: 20:37
 */
public class AnalyzingBook {
    /**
     * 将书写入文件
     * @param books 书的数组
     * @param filename 要写入的文件名
     */
    public void writeBook(Book[] books, String filename) {
        // 先遍历书中有效数据
        int count = 0;
        for (int i = 0; i < books.length; i++) {
            if (books[i] != null) {
                count++;
            }
        }
        StringBuilder stringBuilder = new StringBuilder();
        // 将书数组的每本信息都转化为字符串
        for (int i = 0; i < count; i++) {
            stringBuilder.append(books[i].toStr());
            if (i != count - 1) {
                // 除了最后一行，将每行都拼接杀那个一个换行符\n
                stringBuilder.append("\n");
            }
        }
        FileUtils.writeFile(stringBuilder.toString(),filename);
    }


    /**
     * 从文件中读取书
     * @param filename 文件名
     * @return 返回书这个数组
     */
    public Book[] loadBook(String filename) {

        // 从文件中读取字符串
        String file = FileUtils.readFile(filename);
        // 判断目前字符串是否为空
        if (file == null || file.isEmpty()) {
            return null;
        }

        // 将字符串以\n分割成一本本书的信息

        String[] allBook = file.split("\n");
        Book[] books = new Book[allBook.length];
        for (int i = 0; i < allBook.length; i++) {
            books[i] = toBook(allBook[i]);
        }
        return books;
    }

    /**
     * 将每一行信息字符串都转化为书
     * @param file 每一行的书包含的信息字符串
     * @return 返回的是一本本书
     */
    public Book toBook(String file) {
        String[] bookFile = file.split(",");
        // 每个属性进⾏转化赋值
        int bookId = Integer.parseInt(bookFile[0]);
        String title = bookFile[1];
        String author = bookFile[2];
        String category = bookFile[3];
        int publishYear = Integer.parseInt(bookFile[4]);
        boolean isBorrowed = Boolean.parseBoolean(bookFile[5]);
        int borrowCount = Integer.parseInt(bookFile[6]);
        LocalDate shelfDate = LocalDate.parse(bookFile[7]);

        Book book = new Book(title,author,category,publishYear,shelfDate);
        // 将其他属性设置成读取到的属性
        book.setBookId(bookId);
        book.setBorrowed(isBorrowed);
        book.setBorrowCount(borrowCount);
        return book;
    }
}















